<template>
    <div class="continer">
        <div class="addSpaceBtn">
            <el-button type="primary" @click="addServer" style="float: left;">添加</el-button>
            <el-form :model="search" :inline="true" ref="sc" @submit.native.prevent style="float: right;">
                <el-form-item label="" prop="id">
                    <el-input type="text" v-model="search.id" placeholder="请输入第三方服务id"></el-input>
                </el-form-item>
                <el-form-item label="" prop="name">
                    <el-input type="text" v-model="search.name" placeholder="请输入第三方服务名称"></el-input>
                </el-form-item>
                <el-form-item label="" prop="service_type">
                    <el-input type="text" v-model="search.service_type" placeholder="请输入服务类型"></el-input>
                </el-form-item>
                <el-button type="primary" class="ml_10" @click="()=>{getList()}" native-type="submit">搜索</el-button>
                <el-button @click="resetForm('sc')">重置</el-button>
            </el-form>
        </div>
        <el-table v-loading="tableload" :data="serverData" row-key="id" style="width:100%" default-expand-all stripe border>
            <el-table-column label="编号" prop="id"></el-table-column>
            <el-table-column label="名称" prop="name"></el-table-column>
            <el-table-column label="类型" prop="service_type"></el-table-column>
            <el-table-column label="地址" prop="addr"></el-table-column>
            <el-table-column label="联系人" prop="link_man"></el-table-column>
            <el-table-column label="联系电话" prop="tel"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="()=>{detail(scope.row)}">查看</el-button>
                    <el-button type="text" size="mini" @click="()=>{edit(scope.row)}">修改</el-button>
                    <el-button type="text" size="mini" @click="()=>{del(scope.row.id)}">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加窗口 -->
        <el-dialog
          class="elDialog"
          :title=serverFormTitle
          :visible.sync="addserverVisible"
          width="80%"
          :modal-append-to-body = 'false'
          @close='radioChange'
          >
            <el-form
              :model="addServerData"
              label-width="120px"
              :rules="formRules"
              ref="formRef"
              autocomplete="off"
              class="addSpaceForm"
              >
                <el-form-item label="第三方名称 : " prop="name">
                    <el-input v-model="addServerData.name"></el-input>
                </el-form-item>
                <el-form-item label="服务类型 : " prop="service_type">
                    <el-select v-model="addServerData.service_type" placeholder="请选择">
                        <el-option
                          v-for="item in serverType"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="公司地址 : " prop="addr">
                    <el-input v-model="addServerData.addr"></el-input>
                </el-form-item>
                <el-form-item label="官网地址 : " prop="url">
                    <el-input v-model="addServerData.url"></el-input>
                </el-form-item>
                <el-form-item label="联系人 : " prop="link_man">
                    <el-input v-model="addServerData.link_man"></el-input>
                </el-form-item>
                <el-form-item label="联系电话 : " prop="tel">
                    <el-input v-model="addServerData.tel"></el-input>
                </el-form-item>
                <el-form-item label="签订协议时间 : " prop="agreement_time">
                    <el-date-picker
                      v-model="addServerData.agreement_time"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="合作协议 : " prop="tel">
                    <el-upload
                      class="upload-demo"
                      action="http://scapi.raysightiot.cn/admin/file/upload/createfile"
                      :on-preview="hzxyHandlePreview"
                      :on-remove="hzxyHandleRemove"
                      :on-success="hzxyHandleSuccess"
                      :on-exceed="hzxyHandleExceed"
                      :file-list="hzxyFileList"
                      :limit=hzxylimit>
                      <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="简介 : " prop="content">
                    <vue-ueditor-wrap v-model="addServerData.content" :config="ueConfig"></vue-ueditor-wrap>
                </el-form-item>
                <el-form-item label="封面 : " prop="">
                    <div>
                        <el-radio-group v-model="radio" @change="radioChange">
                            <el-radio label="1">一张封面图</el-radio>
                            <el-radio label="3">三张封面图</el-radio>
                            <el-radio label="0">无封面图</el-radio>
                        </el-radio-group>
                    </div>
                    <div v-if="radio == 1" style="margin-top: 20px;">
                        <el-upload
                          action="http://scapi.raysightiot.cn/admin/file/upload/createfile"
                          list-type="picture-card"
                          :file-list="fileList"
                          :on-success="handleSuccess"
                          :on-remove="handleRemove">
                          <i class="el-icon-plus"></i>
                        </el-upload>
                    </div>
                    <div style="overflow: hidden;" v-if="radio == 3">
                        <div style="float: left; margin-top: 20px; margin-right: 30px; overflow: hidden;">
                            <el-upload
                              action="http://scapi.raysightiot.cn/admin/file/upload/createfile"
                              list-type="picture-card"
                              :file-list="fileListOne"
                              :on-success="handleSuccessOne"
                              :on-remove="handleRemoveOne">
                              <i class="el-icon-plus"></i>
                            </el-upload>
                        </div>
                        <div style="float: left; margin-top: 20px; margin-right: 30px; overflow: hidden;">
                            <el-upload
                              action="http://scapi.raysightiot.cn/admin/file/upload/createfile"
                              list-type="picture-card"
                              :file-list='fileListTwo'
                              :on-success="handleSuccessTwo"
                              :on-remove="handleRemoveTwo">
                              <i class="el-icon-plus"></i>
                            </el-upload>
                        </div>
                        <div style="float: left; margin-top: 20px; margin-right: 30px; overflow: hidden;">
                            <el-upload
                              action="http://scapi.raysightiot.cn/admin/file/upload/createfile"
                              list-type="picture-card"
                              :file-list='fileListThr'
                              :on-success="handleSuccessThr"
                              :on-remove="handleRemoveThr">
                              <i class="el-icon-plus"></i>
                            </el-upload>
                        </div>
                    </div>
                    <div v-if="fengmianbaocuo" class="fengmianbaocuo">请选择封面</div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addServerSubmit">确认</el-button>
                <el-button @click="quxiao">取消</el-button>
            </div>
        </el-dialog>
        <!-- 查看窗口 -->
        <el-dialog
          title="查看"
          :visible.sync="detailServerVisible"
          width="60%"
          @close='radioChange'
          >
            <table class="detailTable">
                <tr><td class="tr">编号：</td><td>{{detailData.id}}</td></tr>
                <tr><td class="tr">名称：</td><td>{{detailData.name}}</td></tr>
                <tr><td class="tr">类型：</td><td>{{detailData.service_type}}</td></tr>
                <tr><td class="tr">地址：</td><td>{{detailData.addr}}</td></tr>
                <tr><td class="tr">官网地址：</td><td>{{detailData.url}}</td></tr>
                <tr><td class="tr">联系人：</td><td>{{detailData.link_man}}</td></tr>
                <tr><td class="tr">联系电话：</td><td>{{detailData.tel}}</td></tr>
                <tr><td class="tr">签订协议时间：</td><td>{{detailData.agreement_time}}</td></tr>
                <tr><td class="tr">合作协议：</td><td style="cursor: pointer;" @click="hezuoxieyi(detailData.agreement)">合作协议.pdf</td></tr>
                <tr>
                    <td class="tr">封面：</td>
                    <td>
                        <div class="fengmian" v-for="(item, index) in detailData.cover" :key="index" v-if="item" >
                            <img :src="BASE_URL + '/' + item" />
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="tr">简介：</td>
                    <td>
                        <div class="cont ql-editor mt_20" v-html="detailData.content"></div>
                    </td>
                </tr>
            </table>
        </el-dialog>
        <!-- 分页 -->
        <el-pagination
            background
            layout="prev, pager, next, jumper"
            :total="listLen"
            :page-size="limit"
            @current-change="toPage"
            :current-page.sync="currentPage"
            class="txt_r mt_20"
        ></el-pagination>
    </div>
</template>

<script>
    import { getinfo, addinfo, delinfo, editinfo } from "../../api/server";
    import VueUeditorWrap from 'vue-ueditor-wrap';
    import {BASE_URL} from '../../config/app.js';
    export default {
        name: "server",
        data() {
            return {
                BASE_URL: '',
                search: {
                    id: '',
                    name: '',
                    service_type: ''
                },
                serverData: [],
                listLen: 0,
                limit: 14,
                currentPage: 1,
                tableload:false,
                addserverVisible: false,
                addServerData: {},
                serverType: [{
                    value: '财税服务',
                    label: '财税服务'
                }, {
                    value: '法律服务',
                    label: '法律服务'
                }, {
                    value: '知识产权',
                    label: '知识产权'
                }, {
                    value: '金融服务',
                    label: '金融服务'
                }, {
                    value: '技术服务',
                    label: '技术服务'
                }, {
                    value: '资质认定',
                    label: '资质认定'
                }, {
                    value: '资产评估',
                    label: '资产评估'
                }, {
                    value: '管理咨询',
                    label: '管理咨询'
                }, {
                    value: '传媒服务',
                    label: '传媒服务'
                }, {
                    value: '人员培训',
                    label: '人员培训'
                }],
                formRules: {
                    name: [{required: true,message: "请输入第三方名称",trigger: "blur"}],
                    service_type: [{required: true,message: "请输入服务类型",trigger: "blur"}],
                    addr: [{required: true,message: "请输入公司地址",trigger: "blur"}],
                    tel: [{required: true,message: "请输入联系电话",trigger: "blur"}],
                    link_man: [{required: true,message: "请输入联系人",trigger: "blur"}],
                    content: [{required: true,message: "请输入简介",trigger: "blur"}],
                    agreement_time: [{required: true,message: "请输入签订协议的时间",trigger: "blur"}],
                },
                // 查看
                detailServerVisible: false,
                detailData: {},
                serverFormTitle: '添加',
                // 百度编辑器
                ueditorMsg: '',
                ueConfig: {
                    // 初始容器高度
                    initialFrameHeight: 300,
                    // 初始容器宽度
                    initialFrameWidth: '100%',
                    // 上传文件接口
                    elementPathEnable: false,
                    wordCount: false,
                    UEDITOR_HOME_URL: '/UEditor/',
                    imageActionName: 'uploadimage', //执行上传图片的action名称,
                    imageFieldName: "file", //提交的图片表单名称
                    imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
                    "fileActionName": "uploadfile",
                    "fileFieldName": "file",
                    "fileAllowFiles": [
                        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
                        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
                        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
                        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
                    ],
                },
                // 上传图片封面
                radio: '1',
                fyList: [[0], [0,1,2], []],
                fyData: [],
                fyUid: [],
                fileList: [],
                fileListOne: [],
                fileListTwo: [],
                fileListThr: [],
                fengmianbaocuo: false,
                // 上传合作协议
                hzxyFile: '',
                hzxyFileList: [],
                hzxylimit: 1
            };
        },
        methods: {
            // 获取空间列表信息
            getList(page=1){
                this.tableload = true;
                getinfo({
                    ...this.search,
                    page: page,
                    per_page: this.limit
                }).then((response) => {
                    if(response.code == 0){
                        this.serverData = response.data.data;
                        this.listLen = response.data.total;
                        this.tableload = false;
                    }else{
                        this.$message.error(response.message);
                    }
                }).catch(() => {
                    this.tableload = false;
                    this.$message.error("列表数据获取失败");
                })
            },
            resetForm(name){
                this.$refs[name].resetFields();
            },
            // 添加空间
            addServer(){
                this.serverFormTitle = '添加';
                this.addserverVisible = true;
                this.addServerData = {};
            },
            // 上传图片封面
            radioChange(){
                this.fyData = [];
                this.fyUid = [];
                this.fileList = [];
                this.fileListOne = [];
                this.fileListTwo = [];
                this.fileListThr = [];
                this.hzxyFileList = [];
            },
            handleRemove(file, fileList) {
                document.getElementsByClassName("el-upload--picture-card")[0].style.display = 'inline-block';
                for(let i = 0; i < this.fyUid.length; i++){
                    if(file.uid == this.fyUid[i].uid){
                        this.fyData.splice(i,1);
                    }
                }
            },
            handleSuccess(response, file, fileList) {
                document.getElementsByClassName("el-upload--picture-card")[0].style.display = 'none';
                this.fyData.push(response.data.key);
                this.fyUid.push({uid: file.uid});
            },
            handleRemoveOne(file, fileList) {
                document.getElementsByClassName("el-upload--picture-card")[0].style.display = 'inline-block';
                for(let i = 0; i < this.fyUid.length; i++){
                    if(file.uid == this.fyUid[i].uid){
                        this.fyData.splice(i,1);
                        this.fyUid.splice(i,1);
                    }
                }
            },
            handleSuccessOne(response, file, fileList) {
                document.getElementsByClassName("el-upload--picture-card")[0].style.display = 'none';
                this.fyData.push(response.data.key);
                this.fyUid.push({uid: file.uid});
            },
            handleRemoveTwo(file, fileList) {
                if(fileList.length <= 1){
                    document.getElementsByClassName("el-upload--picture-card")[1].style.display = 'inline-block';
                    for(let i = 0; i < this.fyUid.length; i++){
                        if(file.uid == this.fyUid[i].uid){
                            this.fyData.splice(i,1);
                            this.fyUid.splice(i,1);
                        }
                    }
                }
            },
            handleSuccessTwo(response, file, fileList) {
                if(fileList.length >= 1){
                    document.getElementsByClassName("el-upload--picture-card")[1].style.display = 'none';
                    this.fyData.push(response.data.key);
                    this.fyUid.push({uid: file.uid});
                }
            },
            handleRemoveThr(file, fileList) {
                if(fileList.length <= 1){
                    document.getElementsByClassName("el-upload--picture-card")[2].style.display = 'inline-block';
                    for(let i = 0; i < this.fyUid.length; i++){
                        if(file.uid == this.fyUid[i].uid){
                            this.fyData.splice(i,1);
                            this.fyUid.splice(i,1);
                        }
                    }
                }
            },
            handleSuccessThr(response, file, fileList) {
                if(fileList.length >= 1){
                    document.getElementsByClassName("el-upload--picture-card")[2].style.display = 'none';
                    this.fyData.push(response.data.key);
                    this.fyUid.push({uid: file.uid});
                }
            },
            // 上传合作协议
            hzxyHandleRemove(file, fileList) {
                console.log(file, fileList);
            },
            hzxyHandlePreview(file) {
                const userAgent = navigator.userAgent;
                if (!!window.ActiveXObject || "ActiveXObject" in window) {
                    alert('推荐谷歌进行文件预览')
                }else{
                    if(this.serverFormTitle == '添加'){
                        window.open(this.BASE_URL + '/' + file.response.data.key) //blob格式地址
                    }else{
                        window.open(this.BASE_URL + '/' + file.url); //blob格式地址
                    }
                }
            },
            hzxyHandleSuccess(response, file, fileList){
                console.log(response)
                if(response.code == 0){
                    this.addServerData.agreement = response.data.key;
                    this.hzxyFileList = [{name: file.name, url: this.addServerData.agreement}];
                }else{
                    this.$message.error("上传文件失败，请重新上传");
                }
            },
            hzxyHandleExceed(files, fileList){
                this.$message.error("只能上传一个合作协议");
            },
            dateFormat(dateData) {
                var date = new Date(dateData)
                var y = date.getFullYear()
                var m = date.getMonth() + 1
                m = m < 10 ? ('0' + m) : m
                var d = date.getDate()
                d = d < 10 ? ('0' + d) : d
                const time = y + '-' + m + '-' + d
                return time
            },
            // 提交表单
            addServerSubmit(){
                this.addServerData.cover = this.fyData.join();
                this.addServerData.cover_num = this.radio;
                this.addServerData.agreement_time = this.dateFormat(this.addServerData.agreement_time);
                console.log(this.addServerData)
                this.$refs['formRef'].validate((valid) => {
                    if (!valid) {return false;}
                    if(this.addServerData.cover_num == '1' || this.addServerData.cover_num == '3'){
                        if(this.addServerData.cover.length == 0){
                            this.fengmianbaocuo = true;
                            return;
                        }else{
                            this.fengmianbaocuo = false;
                        }
                    }else{this.fengmianbaocuo = false;}
                    if(this.serverFormTitle == '添加'){
                        addinfo({
                            ...this.addServerData,
                            hzxy: this.hzxyFile
                        }).then((response) => {
                            if(response.code == 0){
                                this.$message.success("添加成功");
                                this.getList();
                                this.addserverVisible = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        }).catch((error) => {
                            this.$message.error("添加失败");
                        })
                        return;
                    }
                    if(this.serverFormTitle == '修改'){
                        editinfo({
                            ...this.addServerData,
                            agreement: this.hzxyFile
                        }).then((response) => {
                            if(response.code == 0){
                                this.$message.success("修改成功");
                                this.getList();
                                this.addserverVisible = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        }).catch((error) => {
                            this.$message.error("修改失败");
                        })
                        return;
                    }
                })
            },
            quxiao(){
                this.addserverVisible = false;
            },
            toPage(val){
                this.currentPage = val;
                this.getList(val);
            },
            // 操作
            detail(scope){
                this.detailData = scope;
                if(typeof(scope.cover) == 'string'){
                    this.detailData.cover = scope.cover.split(",");
                }else{
                    this.detailData.cover = scope.cover;
                }
                var regex1 = new RegExp("(i?)(\<img)(?!(.*?style=['\"](.*)['\"])[^\>]+\>)","gmi");
                this.detailData.content = this.detailData.content.replace(regex1, `$2 style="display:block;max-width:100%!important;height:auto!important;"$3`);
                this.detailServerVisible = true;
            },
            edit(scope){
                let _this = this;
                this.serverFormTitle = '修改';
                this.addserverVisible = true;
                this.addServerData = scope;
                this.hzxyFileList = [{name: '合作协议.pdf', url: this.addServerData.agreement}];
                this.radio = scope.cover_num.toString();
                let urlStr = null;
                if(typeof(scope.cover) == 'string'){
                    urlStr = scope.cover.split(",");
                }else{
                    urlStr = scope.cover;
                }
                if(scope.cover_num == 1){
                    this.fileList = [];
                    urlStr.forEach(item => {
                        let obj = new Object();
                        obj.url = BASE_URL + '/' + item;
                        _this.fileList.push(obj);
                        _this.fyUid.push(obj);
                        _this.fyData.push(item);
                        setTimeout(function(){
                            document.getElementsByClassName("el-upload--picture-card")[0].style.display = 'none';
                        }, 100)
                    });
                }
                if(scope.cover_num == 3){
                    urlStr.forEach((item, key) => {
                        let obj = new Object();
                        obj.url = BASE_URL + '/' + item;
                        _this.fileList.push(obj);
                        _this.fyUid.push(obj);
                        _this.fyData.push(item);
                        setTimeout(function(){
                            document.getElementsByClassName("el-upload--picture-card")[key].style.display = 'none';
                        }, 100)
                    });
                    this.fileListOne = [];
                    this.fileListTwo = [];
                    this.fileListThr = [];
                    this.fileListOne.push(this.fileList[0]);
                    this.fileListTwo.push(this.fileList[1]);
                    this.fileListThr.push(this.fileList[2]);
                }
            },
            del(delId){
                this.$confirm("确定删除该内容吗", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(()=>{
                    delinfo({id:delId}).then((data)=>{
                        if(data.code){
                            this.$message.error(data.message);
                            return;
                        }
                        this.$message.success("删除成功");
                        this.getList(this.currentPage);
                    }).catch(()=>{
                        this.$message.error("删除失败");
                    })
                }).catch(()=>{
                    this.$message.info("取消删除");
                });
            },
            hezuoxieyi(url){
                if (!!window.ActiveXObject || "ActiveXObject" in window) {
                    alert('推荐谷歌进行文件预览')
                }else{
                    window.open(this.BASE_URL + '/' + url);
                }

            }
        },
        created() {
            this.BASE_URL = BASE_URL;
            this.getList();
        },
        components: {
            VueUeditorWrap
        }
    };
</script>

<style scoped>
.addSpaceBtn{
    width: 100%;
}
.addSpaceForm{
    padding: 10px 30px;
}
.detailTable{font-size:16px;}
.detailTable td{padding:4px 0 22px;}
.detailTable .tr{text-align:right;padding-right:12px; padding-left:0; min-width:100px; vertical-align: top;}

.edui-default .edui-dialog-buttons .edui-label, .edui-default .edui-for-fontfamily .edui-listitem-label, .edui-popup div, .edui-default .edui-dialog-caption {
    color: #000;
}
.displayNone{display: none;}
.fengmian{width: 148px; height: 148px; display: inline-block; margin-right: 20px;}
.fengmian img{width: 100%; height: 100%;}
.fengmianbaocuo{color: #F56C6C; font-size: 12px; line-height: 1; padding-top: 4px; display: block;}
</style>
